// pages/index/chair/index.js
import Toast from "../../../vant/weapp/toast/toast";
import clickreply from "../../../utils/clickreply";
import {
  room
} from "../../../utils/api";
const util = require("../../../utils/util");
const WxParse = require('../../wxParse/wxParse');
const app = getApp()
Page({
  data: {
    index: 0, //默认选择第一个门店
    date: util.formatTimeDay(new Date()),
    seat: [],
    seatIndex: 0,
    way: [],
    wayIndex: 0,
    add: [],
    addIndex: 0,
    seatDetail: "",
    sign: false, //是否已经签到
    isSeat: false, //是否已摇号
    n: 4, //北0东1南2西3
    person: 0, //排队人数
    chair: '',
    is_user_show: true,
    is_user: 0,
    showUser: false,
    pick_show_start: false,
    formatter(type, value) {
      if (type === "year") {
        return `${value}年`;
      } else if (type === "month") {
        return `${value}月`;
      }
      return `${value}日`;
    },
    currentDate_start: new Date().getTime(),
    minDate: new Date().getTime(),
  },
  onLoad() {
    const that = this
    app.http.post(app.api.room, {}, (res) => {
      // console.log(res)
      that.setData({
        room: res.data
      })
      that.getSeat()
      that.getSeatDetail()
    })
    if (wx.getStorageSync('mobile') == "") {
      return
    }
  },
  bindDateChange(e) {
    console.log(e)
    this.setData({
      date: util.formatTimeDay(new Date(e.detail)),
      pick_show_start: false,
    })
  },
  // 日期选择唤起
  select_pick_start(e) {
    if (wx.getStorageSync('mobile') == "") {
      this.login()
      return
    }
    this.setData({
      pick_show_start: true,
    });
  },
  none() {
    if (wx.getStorageSync('mobile') == "") {
      this.login()
      return
    }
    return
  },
  //   登录
  login() {
    if (wx.getStorageSync('token') == "") {
      this.setData({
        is_user_show: false,
        is_user: 1
      });
    } else if (wx.getStorageSync('mobile') == "") {
      this.setData({
        is_user_show: false,
        is_user: 2
      });
    }
  },
  // 登录遮罩层
  close(e) {
    this.setData({
      is_user_show: e.detail,
      is_user: 0,
      pick_show_start: false,
    });
  },
  // 登陆后更新
  renew(e) {
    this.setData({
      showUser: true,
    });
    wx.setStorageSync('userInfo', e.detail)
    wx.setStorageSync('mobile', e.detail.mobile)
  },
  // 门禁
  opendoor(e) {
    console.log(this.data, this.data.seatDetail)
    const that = this
    let i = e.currentTarget.dataset.index
    wx.getLocation({
      type: "wgs84",
      success: function (res) {
        app.http.post(app.api.DoorSeat, {
          order_on: that.data.seatDetail.order_on,
          door_id: that.data.seatDetail.door_list[i].door_id,
          lat: res.latitude,
          lng: res.longitude
        }, res => {
          if (res.code === 200) {
            Toast.success("开门成功")
          } else {
            Toast.fail(res.message)
          }

        })
      },
      fail(e) {
        wx.setStorageSync("openSet", true);
        that.openSet();
      },
    });

  },
  // 打开设置
  openSet() {
    var that = this;
    if (wx.getStorageSync("openSet")) {
      wx.getSetting({
        success: (res) => {
          var statu = res.authSetting;
          if (!statu["scope.userLocation"]) {
            //没授权
            wx.showModal({
              title: '授权',
              content: '如果需要使用定位功能，请点击确定并在授权管理中打开“设置”，打开定位功能。',
              complete: (res) => {
                if (res.confirm) {
                  wx.openSetting({
                    success: function (res) {
                      if (res.authSetting["scope.userLocation"]) {
                        wx.setStorageSync("openSet", false);

                      } // 如果成功打开授权
                      else {
                        wx.setStorageSync("openSet", true);
                        that.setData({
                          latitude: 0,
                          longitude: 0,
                        });

                      } // 如果用户依然拒绝授权
                    },
                    fail: function () {
                      //调用失败，授权登录不成功
                      return;
                    },
                  });
                }

                if (res.cancel) {
                  that.setData({
                    latitude: 0,
                    longitude: 0,
                  });
                }
              }
            })

          }
        },
      });
    }
  },
  // 获取排队人数
  getSeatLineup() {
    const that = this
    let store_id = that.data.room[that.data.index].room_id
    let method_id = that.data.seat[that.data.seatIndex].id
    let seat_id = that.data.way[that.data.wayIndex].id
    let happy_id = that.data.way[that.data.wayIndex].happy_id
    app.http.post(app.api.SeatLineup, {
      store_id,
      method_id,
      seat_id,
      happy_id
    }, (res) => {
      console.log(res)
      that.setData({
        person: res.data.num
      })
    })
  },
  // 获取玩法
  getMethod() {
    const that = this
    let store_id = that.data.room[that.data.index].room_id
    let method_id = that.data.seat[that.data.seatIndex].id
    app.http.post(app.api.SeatMethod, {
      store_id,
      method_id
    }, (res) => {
      if (res.data == "") {
        return
      }
      that.setData({
        way: res.data,
      })
      that.getSeatLineup()
    })
  },
  getSeat() {
    const that = this
    if (wx.getStorageSync('mobile') == "") {
      that.login()
      return
    }
    let store_id = that.data.room[that.data.index].room_id
    app.http.post(app.api.Seat, {
      store_id
    }, (res) => {
      console.log(res.data.room.content)
      that.setData({
        seat: res.data.method,
        add: res.data.room
      })
      that.getMethod()
      WxParse.wxParse('content', 'html', res.data.room.content, that, 5);
    })
  },
  // 切换门店
  bindPickerChange(e) {
    const that = this
    that.setData({
      index: e.detail.value,

    })
    that.getSeat()
    that.getSeatDetail()
  },
  bindSeatChange(e) {
    const that = this;
    that.setData({
      seatIndex: e.detail.value,
      wayIndex: 0
    });
    that.getMethod()
  },
  // 选择方式
  bindWayChange(e) {
    console.log(e);
    const that = this;
    that.setData({
      wayIndex: e.detail.value,
    });
    that.getSeatLineup()
  },

  //摇号定位
  sweepstakes() {
    if (clickreply.preventDuplicateClicks(3)) return;
    const that = this;
    if (wx.getStorageSync('mobile') == "") {
      that.login()
      return
    }
    if (that.data.date < util.formatTimeDay(new Date())) {
      Toast.fail("请正确选择日期")
      return
    }
    let store_id = that.data.room[that.data.index].room_id
    let method_id = that.data.seat[that.data.seatIndex].id
    let seat_id = that.data.way[that.data.wayIndex].id
    let happy_id = that.data.way[that.data.wayIndex].happy_id
    let add_time = that.data.date
    app.http.post(app.api.Lottery, {
      store_id,
      method_id,
      happy_id,
      seat_id,
      add_time
    }, (res) => {
      wx.login({
        success(codes) {
          if (codes.code) {
            app.http.post(app.api.wechat, {
              order_on: res.data.order_on,
              code: codes.code,
              type: 4
            }, (re) => {
              console.log(re)
              wx.requestPayment({
                appid: re.data.appId,
                timeStamp: re.data.timeStamp,
                nonceStr: re.data.nonceStr,
                package: re.data.package,
                signType: re.data.signType,
                paySign: re.data.paySign,
                success(da) {
                  if (da.errMsg == 'requestPayment:ok') {
                    that.setData({
                      isSeat: true
                    })
                    that.getSeatDetail();
                  }
                },
                fail() {
                  that.deleteSeat(res.data.order_on)

                }
              })
            })

          }
        }
      })
    })

  },
  deleteSeat(order_on) {
    app.http.post(app.api.deleteSeat, {
      order_on
    }, (res) => {
      // Toast({
      //   type: 'fail',
      //   message: '预定失败',
      //   onClose: () => {

      //   },
      // });
      console.log(res, order_on)
    })
  },
  // 玩法订单详情
  getSeatDetail() {
    const that = this
    app.http.post(app.api.SeatDetail, {}, (res) => {
      console.log(res)
      if (res.data.is_lottery) {
        let str = res.data.is_lottery
        let arr = str.split("-")
        let seat = arr[1].slice(0, 1)
        // 北0东1南2西3
        if (seat === "南") {
          that.data.n = 2
        } else if (seat === "北") {
          that.data.n = 0
        } else if (seat === "西") {
          that.data.n = 3
        } else if (seat === "东") {
          that.data.n = 1
        }
        console.log(222, that.data.room)
        for (let i = 0; i < that.data.room.length; i++) {
          if (res.data.store_id === that.data.room[i].room_id) {
            that.setData({
              index: i
            })
            console.log(i, res.data.store_id === that.data.room[i].room_id, res.data.store_id, that.data.room[i].room_id)
          }
        }
        that.setData({
          seatDetail: res.data,
          person: res.data.num,
          chair: that.data.n,
          sign: !!res.data.sign,
          isSeat: true
        })
        that.getAwardId()
      } else {
        wx.removeStorageSync('isSeat')
      }
    })
  },
  getAwardId() {
    const that = this;
    if (wx.getStorageSync('isSeat')) {
      that.setData({
        isSeat: true,
        n: that.data.chair
      })
      console.log(that.data.isSeat, that.data.chair)
      return
    }

    // 调取后端接口拿到抽奖后返回的ID
    let n = that.data.n; //北0东1南2西3
    let num_interval_arr = [200, 400];
    // 旋转的总次数
    // 每一圈所需要的时间
    let interval = 0;
    num_interval_arr.forEach((delay, index) => {
      setTimeout(() => {
        this.rotateCircle(delay, index + 1, n);
      }, interval);
      //因为每一圈转完所用的时间是不一样的，所以要做一个叠加操作
      interval += delay * 8;
    });
  },
  // 转圈动画效果
  rotateCircle(delay, ronum, n) {
    const that = this;
    // 多转几圈0 1 2 3 选1，则index为6，共转5个数，传0则转4次
    let index = n + 5;
    for (let i = 0; i < index; i++) {
      setTimeout(() => {
        // 更新状态
        // console.log(delay * i, i % 4, i);
        that.setData({
          n: i % 4, //余数为所选数字
        });
        if (ronum == 2 && i == index - 1) {
          wx.setStorageSync('isSeat', true)
          that.setData({
            isSeat: true,
          });
        }
      }, delay * i);
    }
  },
  isSign(e) {
    const that = this;
    console.log(e.currentTarget.dataset.order)
    wx.getLocation({
      success: function (res) {
        app.http.post(app.api.SeatSing, {
          lat: res.latitude,
          lag: res.longitude,
          order_on: e.currentTarget.dataset.order
        }, (res) => {
          if (res.code === 200) {
            Toast({
              type: 'success',
              message: res.message,
              onClose: () => {
                that.setData({
                  sign: true,
                });
              },
            });
          } else {
            Toast.fail(res.message)
          }

          console.log(res)
        })

      },
      fail: function (fail) {
        Toast({
          type: 'fail',
          message: fail.message,
        });
      }
    })
    // 

  },
});